import {
  Component,
  Injector,
  ViewEncapsulation,
  ViewChild,
  OnInit,
  EventEmitter,
  Output,
  ElementRef
} from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import { MaterialChargeServiceProxy } from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { LazyLoadEvent } from 'primeng/primeng';

@Component({
  selector: 'adjustIntoModal',
  templateUrl: './adjust-into-modal.component.html',
  encapsulation: ViewEncapsulation.None
})
export class AdjustIntoModalComponent extends AppComponentBase {
  @ViewChild('actionModal') modal: ModalDirective;

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;

  id = '';
  event: LazyLoadEvent;
  positionId = 0;

  quantity = undefined;
  weight = undefined;
  totalPrice = undefined;
  isHaveCost =false;

  remark = '';

  constructor(
    injector: Injector,
    private _materialChargeServiceProxy: MaterialChargeServiceProxy
  ) {
    super(injector);
  }

  show(id: string, event?: LazyLoadEvent): void {
    this.positionId = 0;
    this.event = event;
    this.active = true;
    this.quantity = undefined;
    this.weight = undefined;
    this.totalPrice = undefined;
    this.remark = '';
    this.id = id;

    this._materialChargeServiceProxy.isHaveMaterialChargeCost(id).subscribe(result => {
      this.isHaveCost=result;
    });

    console.log(this.isHaveCost);

    setTimeout(() => {
      this.modal.show();
    }, 0);
  }

  save(): void {
    if (!this.positionId) {
      this.notify.error('请选择一个位置');
      return;
    }

    if (!this.quantity) {
      this.notify.error('调整库存增数量不能为0');
      return;
    }

    this.saving = true;

    this._materialChargeServiceProxy
      .adjustInto(
        this.id,
        this.positionId,
        this.quantity,
        this.weight,
        this.remark,
        this.totalPrice
      )
      .pipe(
        finalize(() => {
          this.saving = false;
        })
      )
      .subscribe(result => {
        this.close();
        this.modalSave.emit(this.event);
        this.notify.success('调整库存增成功');
      });

  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }
}
